<?php

namespace app\model\agency;

use app\base\BaseModel;
use app\model\goods\GoodsModel;
use app\model\order\PayLogModel;
use think\facade\Cache;
use think\facade\Db;

/**
 * 模型-AgencyOrderModel
 * Class AgencyOrderModel
 * @package app\model
 */
class AgencyOrderModel extends BaseModel
{

    protected $name = 'agency_order';

    /**
     * handle_status
     * @param $query
     * @param $handle_status
     */
    public function scopeHandleStatus($query, $handle_status)
    {

        if (!empty($handle_status)) {
            $query->where('a.handle_status', $handle_status);
        }

    }

    /**
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('a.order_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.pay_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.agency_id', '%' . trim($keyword) . '%');
        }
    }

    /**
     * 获取分页列表
     * @param $handle_status
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @return array
     */
    public function getPageData($handle_status, $keyword, $current_page, $list_rows)
    {
        $dataList = $this
            ->alias("a")
            ->join("t_agency c", "a.agency_id=c.id")
            ->field("a.*,c.agency_title,c.agency_img")
            ->handleStatus($handle_status)
            ->keyword($keyword)
            ->order('a.id', 'desc')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 添加进货订单
     * @param $order_data
     * @param $agency_id
     * @param $address
     * @param string $buy_msg
     * @return array
     * @throws \Exception
     */
    public function addOrder($order_data, $agency_id, $address, $buy_msg = "")
    {
        $return_data = [
            'code' => 991,
            'msg' => "参数有误"
        ];
        $goods_data = $order_data['data'];
        $order_keyword = $order_data['keyword'];
        $order_total = $order_data['total'];
        if (empty($goods_data)) {
            return $return_data;
        }
        $this->startTrans();
        $order_sn = date("YmdHis") . $agency_id . mt_rand(1000, 9999);
        $in_data = [
            'order_sn' => $order_sn,
            'agency_id' => $agency_id,
            'order_keyword' => $order_keyword,
            'address' => $address,
            'buy_msg' => $buy_msg,
            'status' => 2,
            'order_total' => $order_total,
            'add_time' => time(),
            'add_date' => date("Y-m-d H:i:s")
        ];
        $ret = $this->save($in_data);
        if ($ret !== false) {
            $order_id = $this->getLastInsID();
            $in_order_item = [];
            foreach ($goods_data as $value) {
                $in_order_item[] = [
                    'order_id' => $order_id,
                    'agency_id' => $agency_id,
                    'goods_id' => $value['goods_id'],
                    'goods_price' => $value['goods_agency_price'],
                    'goods_number' => $value['goods_number'],
                    'order_total' => floatval($value['goods_agency_price']) * intval($value['goods_number']),
                ];
            }
            $agency_order_item_model = new AgencyOrderItemModel();
            $retx = $agency_order_item_model->saveAll($in_order_item);
            if ($retx !== false) {
                $this->commit();
                $return_data = [
                    'code' => 1,
                    'msg' => "添加成功"
                ];
                return $return_data;
            }
        }
        $this->rollback();
        $return_data = [
            'code' => 0,
            'msg' => "添加失败"
        ];
        return $return_data;
    }

    /**
     * 获取代理商支付信息
     * @param string $order_id
     * @param string $user_id
     * @param string $pay_mode
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderPayInfo($order_id = '', $user_id = '', $pay_mode = 'weixin')
    {
        $pay_sn = Cache::store('redis')->get($this->redis_key . 'agency' . $order_id, 0);
        if (empty($pay_sn)) {
            $pay_sn = "agency" . date("YmdHis") . $order_id . rand(1000, 9999);
            Cache::store('redis')->set($this->redis_key . 'agency' . $order_id, $pay_sn, 600);
        }
        $map = [
            'id' => $order_id,
            'user_id' => $user_id,
            'status' => 1
        ];
        $order_data = $this->where($map)->find();
        if (empty($order_data)) {
            throw new \think\Exception("支付信息不存在！", 0);
        }
        $order_id = $order_data['id'];
        $order_sn = $order_data['order_sn'];
        Db::startTrans();
        $agency_order_item_model = new AgencyOrderItemModel();
        $order_item = $agency_order_item_model->getChildInfo($order_id, $pay_sn);
        $goods_item = [];
        $order_total = 0;
        foreach ($order_item as $value) {
            $goods_item[] = $value;
            $order_total += floatval($value['order_total']);
        }
        $up_pay = [
            'pay_sn' => $pay_sn,
        ];
        $ret = $this->where($map)->update($up_pay);
        $out_data = [
            'order_id' => $order_id,
            'order_sn' => $order_sn,
            'pay_sn' => $pay_sn,
            'total' => $order_total,
            'item' => $goods_item
        ];
        if ($ret !== false) {
            PayLogModel::addLog($out_data, "pay", $pay_mode);
            Db::commit();
        } else {
            Db::rollback();
            return [];
        }
        return $out_data;
    }

    /**
     * 代理商支付回调
     * @param string $pay_sn
     * @return bool
     */
    public function endOrderPay($pay_sn = '')
    {
        $map = [
            'pay_sn' => $pay_sn
        ];
        $up_pay = [
            'status' => 2
        ];
        $this->startTrans();
        $ret = $this->where($map)->update($up_pay);
        if ($ret !== false) {
            $this->commit();
            return true;
        }
        $this->rollback();
        return false;
    }

    /**
     * 审核代理商进货单
     * @param $id
     * @param int $admin_id
     * @param int $handle_status
     * @param string $remark
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkOrder($id, $handle_status, $admin_id = 0, $remark = '')
    {
        $return_data = [
            'code' => 0,
            'msg' => "审核失败"
        ];
        $order_data = $this->where(['id' => $id])->find();
        if (empty($order_data)) {
            $return_data['msg'] = "进货单不存在";
            return $return_data;
        }
        if (intval($order_data['handle_status']) == 1) {
            if (intval($handle_status) == 3) {
                $ret = $this->where(['id' => $id])->update(['handle_status' => $handle_status]);
                if ($ret !== false) {
                    return $return_data;
                }
                $return_data = [
                    'code' => 1,
                    'msg' => "审核成功"
                ];
                return $return_data;
            }
            $agency_order_item_model = new AgencyOrderItemModel();
            $goods_list = $agency_order_item_model->getItemByGoodsId($id);
            if (empty($goods_list)) {
                $return_data['msg'] = "进货单数据有误";
                return $return_data;
            }

            $up_order = [
                'handle_status' => $handle_status,
                'handle_time' => date("Y-m-d H:i:s"),
                'remark' => $remark
            ];
            $this->startTrans();
            $ret = $this->where(['id' => $id])->update($up_order);
            if ($ret !== false) {
                foreach ($goods_list as $value) {
                    $goods_model = new GoodsModel();
                    $goods_id = $value['goods_id'];
                    $storage = [
                        'storage' => $value['goods_number'],
                        'target_id' => $order_data['agency_id'],
                    ];
                    $operate = [
                        'operate' => 'agency',
                        'admin_id' => $admin_id
                    ];
                    $change = "add";
                    $remark = "进货单审核商品增加库存";
                    $ret = $goods_model->changeStore($goods_id, $storage, $change, 0, $operate, $remark);
                    if ($ret === false) {
                        $return_data = [
                            'code' => 0,
                            'msg' => "商品库存不足"
                        ];
                        $this->rollback();
                        return $return_data;
                    }
                }
                if ($ret === false) {
                    $this->rollback();
                } else {
                    $this->commit();
                    $return_data = [
                        'code' => 1,
                        'msg' => "审核成功"
                    ];
                    return $return_data;
                }
            }
            $this->rollback();
            return $return_data;
        } else {
            $return_data['msg'] = "进货单已经处理";
            return $return_data;
        }
    }
}
